package com.sunny.service.impl;

import java.util.Date;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.sunny.dao.IUserDao;
import com.sunny.model.User;
import com.sunny.query.UserQuery;
import com.sunny.service.IUserService;

import framework.base.BaseService;
import framework.utils.DateUtils;

/**
 * 用户表 [Service实现类]
 * 
 * @ClassName: UserService
 * @Description:
 * @author baolin.liu Email:543847778@qq.com
 * @date 2016-08-05 14:08:15
 * @version V1.0
 */
@Service
public class UserService extends BaseService<User> implements IUserService {
	private Log log = LogFactory.getLog(UserService.class);

	@Resource
	private IUserDao userDao;

	public IUserDao getBaseDao() {
		return userDao;
	}

	@Override
	public void updateFailTimeByUserId(String userId, boolean loginSucc) {
		UserQuery uq = new UserQuery();
		uq.setUserId(userId);
		User user = userDao.selectOne(uq);
		Date dateNow = new Date();
		if (loginSucc) {
			user.setFailTime(0);
			user.setLoginTime(dateNow);
		} else {
			Date loginTime = user.getLoginTime();

			if (loginTime == null || !DateUtils.isSameDay(loginTime, dateNow)) {
				user.setFailTime(1);
				user.setLoginTime(dateNow);
				userDao.updateFailTimeByUserId(user);
			} else {
				Integer failTime = user.getFailTime() == null ? 1 : user.getFailTime() + 1;
				if (failTime < 5) {
					user.setFailTime(failTime);
					user.setLoginTime(dateNow);
					userDao.updateFailTimeByUserId(user);
				} else {
					user.setFailTime(0);
					user.setStatus(4);
					user.setLoginTime(dateNow);
					userDao.updateFailTimeByUserId(user);
					userDao.updateStatusByUserId(user);
				}
			}
		}
	}

	@Override
	public void updateStatusByUserId(User u) {
		userDao.updateStatusByUserId(u);
	}

}